//
//  NewFeatureViewController.swift
//  Weibo
//
//  Created by 张婷 on 15/10/22.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit
import SnapKit
/// 可重用标识符
private let WBNewFeatureViewCellId = "WBNewFeatureViewCellId"

/// 新特性图片数量
private let WBNewFeatureCount = 4

/// 新特性界面
class NewFeatureViewController: UICollectionViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.prepareForCollection()
        
        // 注册 cell
        collectionView?.registerClass(NewFeatureCell.self, forCellWithReuseIdentifier: WBNewFeatureViewCellId)
    }
    
    ///  设置 collection 的属性
    private func prepareForCollection() {
        collectionView?.backgroundColor = UIColor.whiteColor()
        collectionView?.pagingEnabled = true
        collectionView?.bounces = false
        collectionView?.showsHorizontalScrollIndicator = false
    }
    
    // MARK: - 构造函数
    init() {
        
        let layout = UICollectionViewFlowLayout()
        
        layout.itemSize = UIScreen.mainScreen().bounds.size
        layout.scrollDirection = .Horizontal
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        
        
        super.init(collectionViewLayout: layout)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    ///  隐藏状态栏
    override func prefersStatusBarHidden() -> Bool {
        return true
    }
}

// MARK: 数据源方法
extension NewFeatureViewController {
    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return WBNewFeatureCount
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(WBNewFeatureViewCellId, forIndexPath: indexPath) as! NewFeatureCell
        
        cell.imageIndex = indexPath.item
        return cell
    }
}

// MARK: 代理方法
extension NewFeatureViewController {
    
    ///  停止滚动的方法
    ///
    ///  - parameter scrollView: <#scrollView description#>
    override func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        
        // 获取 indexPath
        let offset = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        if offset != WBNewFeatureCount - 1 {
            return
        }
        
        // 启动动画
        let cell = collectionView?.cellForItemAtIndexPath(NSIndexPath(forItem: offset, inSection: 0)) as? NewFeatureCell
        cell?.showButtonAnim()
        
    }


}

// MARK: 新特性 cell
private class NewFeatureCell: UICollectionViewCell {
    
    /// 图像索引
    var imageIndex = 0 {
        
        didSet {
            // 图像名称是以 1 开始的
            iconView.image = UIImage(named: "new_feature_\(imageIndex + 1)")
            startButton.hidden = true
        }
    }
    
    /// 点击启动按钮
    @objc private func clickStartButton() {
        
        // 切换控制器
        NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootviewControllerNotification, object: nil)
    }
    
    ///  显示按钮动画
    private func showButtonAnim() {
        startButton.hidden = false
        startButton.transform = CGAffineTransformMakeScale(0, 0)
        startButton.userInteractionEnabled = true
        
        UIView.animateWithDuration(0.5,       // 动画时间
            delay: 0,                         // 延迟时间
            usingSpringWithDamping: 0.6,      // 弹力系数
            initialSpringVelocity: 10,        // 初始速度
            options: [],                      // 动画选项
            animations: { () -> Void in
                
                // 长和宽变为原来的状态
                self.startButton.transform = CGAffineTransformIdentity
                
            },completion: { (_) -> Void in
                
                self.startButton.userInteractionEnabled = true
        })
       
    }
    
    // MARK: 构造函数，设置界面
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    ///  MARK: 设置布局
    private func setupUI() {
        
        // 添加子控件
        contentView.addSubview(iconView)
        contentView.addSubview(startButton)
        
        iconView.frame = contentView.bounds
        
        startButton.layer.cornerRadius = 5
        startButton.layer.masksToBounds = true
        
        // 设置自动布局
        startButton.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(snp_centerX)
            make.bottom.equalTo(snp_bottom).multipliedBy(0.7)
        }
        
        startButton.addTarget(self, action: "clickStartButton", forControlEvents: .TouchUpInside)
        

    }
    
    /// MARK: 懒加载控件
    private lazy var iconView = UIImageView()
    
    private lazy var startButton: UIButton = UIButton(title: "开始体验", color: UIColor.whiteColor(), backImageName: "new_feature_finish_button")
}